package com.example.basic.schedule;

import com.example.basic.dao.CornMapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author mjw
 * @date 2023/8/21
 * 测试定时任务的使用
 */
//@Component
public class ScheduleTask implements SchedulingConfigurer {

    @Autowired
    private CornMapper cornMapper;

    /**
     * 每五秒钟执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void execute() {
        process();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::process,
                triggerContext -> {
                    String corn = cornMapper.selectCornById(10002);
                    if (corn.isEmpty()) {
                        System.out.println("Corn is null!");
                    }
                    return new CronTrigger(corn).nextExecutionTime(triggerContext);
                });
    }

    public void process() {
        String now = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(now + "执行了一次调度任务。");
    }


}
